package com.dispacher;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dispacher.config.Constants;
import com.dispacher.context.ContextHolder;
import com.dispacher.log.LogFactory;
import com.dispacher.log.Logger;
import com.dispacher.processor.Processor;
import com.dispacher.processor.ProcessorFactory;

/**
 * 该类用于完成从request获取的url到具体的执行类的分发操作， Servlet implementation class
 * DispatcherServlet
 */
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger log = LogFactory.getDefaultLog();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DispatcherServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.log(" doGet() ");
		doExecute(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.log(" doPost() ");
		doExecute(request, response);
	}

	/**
	 * 完成方法分发的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doExecute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ContextHolder holder = ContextHolder.findInstance();
		holder.setRequest(request);
		holder.setResponse(response);
		String url = ContextHolder.findInstance().getRequestUrl();
		Processor processor = ProcessorFactory.createProcessorByUri(url);
		String dispatcherUrl = processor.doProcess();
		if (dispatcherUrl == null) {
			return;
		}
		log.log("with the return url : " + dispatcherUrl);
		holder.dispatcherUrl(dispatcherUrl);
	}
}
